package com.mpower.portlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.PortletPreferencesFactoryUtil;
import com.liferay.portlet.expando.model.ExpandoColumn;
import com.liferay.portlet.expando.model.ExpandoTable;
import com.liferay.portlet.expando.model.ExpandoValue;
import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil;
import com.liferay.portlet.expando.service.ExpandoRowLocalServiceUtil;
import com.liferay.portlet.expando.service.ExpandoValueLocalServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.mpower.service.DynaTableLocalServiceUtil;
import com.mpower.service.impl.DynaTableLocalServiceImpl;

/**
 * Portlet implementation class DynaTablePortlet
 */
public class DynaTablePortlet extends MVCPortlet {

	protected final Log _log = LogFactory.getLog(getClass());
	
	@Override
	public void doView(RenderRequest renderRequest,
			RenderResponse renderResponse) throws IOException, PortletException {

		long dynaTableId = 0;
		String dynaTableName = StringPool.BLANK;
			
		HttpServletRequest request = PortalUtil.getHttpServletRequest(renderRequest);
		PortletPreferences preferences = renderRequest.getPreferences();
		String portletResource = ParamUtil.getString(request, "portletResource");
		
		if (Validator.isNotNull(portletResource)) {
			try {
				preferences = PortletPreferencesFactoryUtil.getPortletSetup(request, portletResource);
			} catch (SystemException e) {
				e.printStackTrace();
			}
		}
		dynaTableId = GetterUtil.getLong(preferences.getValue("dynaTableId", StringPool.BLANK), 0);
		dynaTableName = preferences.getValue("dynaTableName", StringPool.BLANK);
		
		if (Validator.isNotNull(dynaTableName) && Validator.isNotNull(dynaTableId)){
			viewJSP = "/html/list.jsp";
		} else {
			viewJSP = "/html/view.jsp";
		}
		super.doView(renderRequest, renderResponse);
	}
	
	public void listPage(RenderRequest renderRequest,
			RenderResponse renderResponse, String tableName, long tableId) throws IOException, PortletException {
		
		long companyId = PortalUtil.getCompanyId(renderRequest);
		
		try {
			List<ExpandoColumn> expandoColumns = ExpandoColumnLocalServiceUtil.getColumns(companyId,
					DynaTableLocalServiceImpl.class.getName(), tableName);
			Map<String, List<ExpandoValue>> map = new HashMap<String, List<ExpandoValue>>();
			
			for(ExpandoColumn expandoColumn : expandoColumns){
				List<ExpandoValue> expandoValues = ExpandoValueLocalServiceUtil.getColumnValues(expandoColumn.getColumnId(),
						0, ExpandoValueLocalServiceUtil.getColumnValuesCount(expandoColumn.getColumnId()));
				List<ExpandoValue> list = new ArrayList<ExpandoValue>();
				for(ExpandoValue expandoValue : expandoValues){
					list.add(expandoValue);					
				}
				map.put(expandoColumn.getName(), list);
			}
						
			renderRequest.setAttribute("expandoTableMap", map);
			
		} catch (SystemException e) {
			e.printStackTrace();
		}
		
		viewJSP = "/html/list.jsp";
	}
	
	public void addRow(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {
		
		String dynaTableName = ParamUtil.getString(actionRequest, "dynaTableName");
		long companyId = PortalUtil.getCompanyId(actionRequest);
		Enumeration<String> enumeration = actionRequest.getParameterNames();
		
		Map<String, String> fieldsMap = new HashMap<String, String>();
		while (enumeration.hasMoreElements()) {
			String key = (String) enumeration.nextElement().trim();
			if(key.contains("?")){
				String[] columnArray = StringUtil.split(key, "?");
				fieldsMap.put(columnArray[0], ParamUtil.getString(actionRequest, key));
			}
		}
		
		try {
			DynaTableLocalServiceUtil.addValue(companyId, dynaTableName, fieldsMap);
		} catch (SystemException e) {
			e.printStackTrace();
		} catch (PortalException e) {
			e.printStackTrace();
		}
	}
	
	public void addTable(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {

		String tableName = ParamUtil.getString(actionRequest, "tableName");
		
		HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
		PortletPreferences preferences = actionRequest.getPreferences();
		String portletResource = ParamUtil.getString(request, "portletResource");
		
		if (Validator.isNotNull(portletResource)) {
			try {
				preferences = PortletPreferencesFactoryUtil.getPortletSetup(request, portletResource);
			} catch (SystemException e) {
				e.printStackTrace();
			}
		}		
		
		preferences.setValue("dynaTableName", tableName);
		preferences.store();	
		
		actionResponse.setRenderParameter("jspPage", "/html/addColumn.jsp");
	}
	
	public void addColumn(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {
		
		String[] columnNames = actionRequest.getParameterValues("columnName");
		int[] columnTypes = ParamUtil.getIntegerValues(actionRequest,
				"columnType");		
		String tableName = StringPool.BLANK;
		
		long tableId = 0l;
		long companyId = PortalUtil.getCompanyId(actionRequest);
		
		HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
		PortletPreferences preferences = actionRequest.getPreferences();
		String portletResource = ParamUtil.getString(request, "portletResource");
		
		if (Validator.isNotNull(portletResource)) {
			try {
				preferences = PortletPreferencesFactoryUtil.getPortletSetup(request, portletResource);
			} catch (SystemException e) {
				e.printStackTrace();
			}
		}
		tableName = preferences.getValue("dynaTableName", StringPool.BLANK);
		try {
			ExpandoTable expandoTable = DynaTableLocalServiceUtil.addTable(
					companyId, tableName);
			tableId = expandoTable.getTableId();
			preferences.setValue("dynaTableId", String.valueOf(tableId));
			preferences.store();
			
			for (int i = 0; i < columnNames.length; i++) {
				DynaTableLocalServiceUtil.addColumn(tableId, columnNames[i],
						columnTypes[i]);
			}
		} catch (PortalException e) {
			e.printStackTrace();
		} catch (SystemException e) {
			e.printStackTrace();
		}
	}	
	
	public void deleteRows(ActionRequest actionRequest,
			ActionResponse actionResponse) throws Exception {
		
        String tableId = actionRequest.getParameter("tableId");
        String[] rowsId = actionRequest.getParameterValues("rowsId");
        for (String rowId : rowsId){
        	if (Validator.isNotNull(rowId))
        		ExpandoRowLocalServiceUtil.deleteRow(new Long(tableId), new Long(rowId));
        }
/*        
        
        
        long[] l = new long[rowsId.length];
        for (int i = 0; (i < l.length); i++) {
		    if (Validator.isNotNull(rowsId[i])) {
		        l[i] = new Long(rowsId[i]);
		        ExpandoRowLocalServiceUtil.deleteRow(new Long(tableId), l[i]);
		    }
        }*/
		actionResponse.setRenderParameter("jspPage", "/html/list.jsp");
	}
}